//
//  UINavigationController+LYAdd.m
//  LYDevelopKit
//
//  Created by 李阳 on 2018/5/26.
//
#import "UINavigationController+LYAdd.h"
#import "LYUIMacros.h"

LYSYNTH_DUMMY_CLASS(UINavigationController_LYAdd)

@implementation UINavigationController (LYAdd)

- (BOOL)isOnlyContainRootViewController
{
    return self.viewControllers.count == 1;
}

- (UIViewController *)rootViewController
{
    if (self.viewControllers.count) return self.viewControllers.firstObject;
    return nil;
}

- (UIViewController *)searchViewControllerWithClass:(Class)cls
{
    NSUInteger index = [self.viewControllers indexOfObjectPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
        return [obj isKindOfClass:cls];
    }];
    
    if (index == NSNotFound)
    {
        return nil;
    }
    else
    {
        return self.viewControllers[index];
    }
}

- (NSArray<UIViewController *> *)popToViewControllerWithClass:(Class)cls animated:(BOOL)animated
{
    UIViewController *vc = [self searchViewControllerWithClass:cls];
    if (!vc) return nil;
    return [self popToViewController:vc animated:animated];
}

- (NSArray<UIViewController *> *)popToViewControllerWithLevel:(NSInteger)level animated:(BOOL)animated
{
    if (level < 1) return nil;
    NSInteger count = self.viewControllers.count;
    if (level >= count) return [self popToRootViewControllerAnimated:animated];
    UIViewController *vc = self.viewControllers[count - level - 1];
    return [self popToViewController:vc animated:animated];
}

- (void)setItemTitleTextAttributes:(NSDictionary<NSAttributedStringKey,id> *)attributes forState:(UIControlState)state
{
    UIBarButtonItem *item = [UIBarButtonItem appearanceWhenContainedIn:[self class], nil];
    [item setTitleTextAttributes:attributes forState:state];
}

@end


